package com.example.demospringboot.netty.custom.ecodc;

import com.alibaba.fastjson.JSON;
import com.example.demospringboot.netty.custom.procotol.ComPack;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author chenlei
 * @date 2020/1/17
 * @description
 **/
public class ComPackToByteEncoder extends MessageToByteEncoder<ComPack> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ComPack comPack, ByteBuf byteBuf) throws Exception {
        byte [] bytes = JSON.toJSONString(comPack).getBytes();
        //先写入头信息，数据的长度
        byteBuf.writeInt(bytes.length);
        //写入数据
        byteBuf.writeBytes(bytes);
    }
}
